// 1.导入express对象
const express = require('express')
// 2.创建路由对象
const router = express.Router()
// 3.编写接口
const { getAll, getOne, exec } = require('../db')
/**
 * 获取所有公告
 * GET /user
 */
router.get('/', async (req, res, next) => {
  // 获取所有公告
  let sql = `SELECT * from gg_notice`
  const data = await getAll(sql)
  // 获取公告数量
  sql = `select count(*) as total from gg_notice`
  const { total } = await getOne(sql)
  res.send({
    code: 0,
    message: '获取所有公共成功',
    result: {
      total,
      data,
    },
  })
})

/**
 * 获取单条公告 以及生效区域
 * Get /id
 *  */

router.get('/:id', async (req, res, next) => {
  const { id } = req.params
  let sql = `select * from gg_notice where notice_id=${id}`
  const data = await getOne(sql)
  res.send({
    code: 0,
    message: '查询此公告成功',
    result: data,
  })
})

/**
 * 增加公告
 * @param {user_id} 确定发布人
 * @params {notice_title}
 * @params {notice_contents}
 * @params {notice_time}
 * @params {notice_public}
 */
router.post('/', async (req, res, next) => {
  const { id, title, content, unit } = req.body
  let sql = `insert into gg_notice(user_id,notice_title,notice_content,notice_public) values('${id}','${title}','${content}','${unit}')`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '新增公告成功',
  })
})

/** 删除单个公告
 *  delete /id
 */

router.delete('/:id', async (req, res, next) => {
  const { id } = req.params
  try {
    let sql = `delete from gg_notice where notice_id=${id} `
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '删除此公告成功',
      result: '',
    })
  } catch (e) {
    console.error(e)
  }
})

// 4.导出路由对象
module.exports = router
